<?php

namespace App\Common\Listener;

use App\Common\Model\Model;
use think\db\Query;

/**
 * Class JoinSelectSoftDeleteListener
 */
class JoinSelectSoftDeleteListener
{
    public function handle(Query $query): void
    {
        $joins = $query->getOptions('join');
        if (!$joins) {
            return;
        }

        foreach ($joins as &$join) {
            $tableInfo = $join[0];
            $alias     = current($tableInfo);

            if (!preg_match("/$alias\.delete_time/i", $alias)) {
                $join[2] = sprintf("%s AND %s.delete_time IS NULL", $join[2], $alias);
            }
        }

        unset($join);
        $query->setOption('join', $joins);
    }
}